/**
 * 文章路由
 */

var router = require('express').Router();
var articleTool = require('../bin/article');
var articleMarkTool = require('../bin/articleMark');
var assertAlljs = require('../bin/util/assert-alljs');
var datetimeTool = require('../bin/util/datetime');

router.get('/article(.*)?', async function(req, res) {
    let assert = assertAlljs(req, res);
    if (await assert(typeof(req.query.id) !== 'string' || req.query.id === '', '缺少请求参数'))
        return;

    let result = await articleMarkTool.handleAccess(req.query.id);
    if (await assert(result instanceof Error, '查询数据库错误'))
        return;

    let article = result.value;
    if (article.status === 1){
        await req.session.pushMessage('文章被屏蔽');
        res.redirect('./');
        return;
    }

    article._id = article._id.toString();

    let local = articleTool.toLocalFull(article);
    if (local.content == null)
        local.content = '<p>[系统异常:没有找到文章内容]</p><p><a href="./">返回首页</a></p>';

    local.edit = 'user' in req.session && (
        (req.session.user.role === 'admin')
        ||  req.session.user._id === local.produceUser._id && (new Date().getTime() -  local.produceTime) < 30 * 3600 * 1000);

    if (typeof(local.publish) === 'number')
        local.publish =  datetimeTool.to_yMdHm(local.publish);
    if (typeof(local.produceTime) === 'number')
        local.produceTime =  datetimeTool.to_yMdHms(local.produceTime);
    if (typeof(local.modifyTime) === 'number')
        local.modifyTime =  datetimeTool.to_yMdHms(local.modifyTime);
    local.modify.forEach((modify) => {
        modify[0] = local.produceUser._id === modify[0] ? '用户'+modify[0] : '管理员'+modify[0];
        modify[1] = datetimeTool.to_yMdHms(modify[1]);
    });

    res.render('dyn.article.html', local);
});

module.exports = router;